/* eslint-disable no-undef */
const net = require("net");
const fs = require('fs');
const compare = p => (m, n) => m[p] - n[p];
var clientLoadArray = new Array();
const server = net.createServer((c) => {
  // 'connection' listener.
  console.log("client %s connected", c.address().address);
  c.on("end", () => {
    console.log("client %s disconnected", c.address().address);
  });
  c.write("hello\r\n");
  c.on("data", (data) => {
    computeLoad(JSON.parse(data.toString()), clientLoadArray);
    console.log(clientLoadArray);
  });
  c.pipe(c);
});
server.on("error", (err) => {
  throw err;
});
server.listen(8124, () => {
  console.log("server bound");
});

let computeLoad = function (data, clientLoadArray) {
  let flag = false;
  load =data.throughput * 0.25 + data.memory_ratio * 0.25 + data.cpu_ratio * 0.5;
  var newClient = { address: data.address, load: load };
  if (clientLoadArray.length === 0) {
    clientLoadArray.push(newClient);
    flag = true;
  } else {
    clientLoadArray.forEach((element,index, input) => {
      if (newClient.address === element.address) {
        // element.load = newClient.load;
        flag = true;
        input[index].load = newClient.load
      }
    });
  }
  if (flag === false) {
    clientLoadArray.push(newClient);
  }
  clientLoadArray.sort(compare('load'))
  //将负载最小的节点存入文件
  fs.writeFile('message.json', JSON.stringify(clientLoadArray[0]), (err) => {
    if (err) {
        console.error(err);
     }else{
         console.log('----------最小负载节点写入成功-------------');
     }
  });
};
